<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- <el-button type="primary">主要按钮</el-button> -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="params.query" clearable @clear="resUserList">
            <el-button slot="append" icon="el-icon-search" @click="resUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加按钮</el-button>
        </el-col>
      </el-row>
      <el-table :data="userlist" :border="true" :stripe="true">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" >
          <!-- 自定义插槽 -->
        <template v-slot:default="{row}">
          <!-- {{row.mg_state}} -->
          <el-switch v-model="row.mg_state" @change="UserStateChange(row)"></el-switch>
        </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot:default="scope">
            <!-- 修改用户按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除用户按钮 -->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
          <!-- 设置文字提示 -->
          <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
            <!-- 修改权限按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column> -->
      </el-table>
      <!-- 这里是分页的页面 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <!-- 这个close事件好像是dialog专属的事件 -->
    <el-dialog
  title="添加用户"
  :visible.sync="addDialogVisible"
  width="50%" @close="addDialogClosed"> 
  <!-- 内容体 -->
  <el-form :model="addForm" :rules="addFormRules" ref="addFromRef" label-width="70px">
  <!-- 用户名 -->
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <!-- 密码 -->
  <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
  <!-- 邮箱 -->
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
  <!-- 电话 -->
  <el-form-item label="电话" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>


<!-- 修改用户 -->
<el-dialog
  title="修改用户"
  :visible.sync="editDialogVisible"
  width="50%" @close="editDialogClose">
  <el-form :model="editForm" :rules="editFromRules" ref="editFromRef" label-width="70px">
  <el-form-item label="用户名">
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
  <el-form-item label="电话" prop="mobile">
    <el-input v-model="editForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo()">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
// 导入请求数据的函数
import { getUserList, putChangeState ,addUser ,getUserById,editUser, deleteUserReq} from 'network/users'
// 
export default {
  name: 'User',
  created() {
    this.resUserList()
  },
  data() {
    // 自定义校验规则 加其加入校验规则对象中 用validator接收 这里的test是正则表达式的函数
    // 邮箱校验 
    const cheakEmail = (rule,value,cb) => {
      const regEmail = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(regEmail.test(value)) return cb()
      return cb(new Error('请输入合法邮箱'))
    }
    // 电话校验
    const cheakMobile = (rule,value,cb) => {
      const regMobile = /(^0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if( regMobile.test(value) ) return cb()
      cb(new Error('请输入合法的手机号'))
    }
    return {
      params: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: cheakEmail, trigger: 'blur'}
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: cheakMobile, trigger: 'blur'}
        ],
      },
      editDialogVisible: false,
      editForm: {},
      editFromRules:{
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: cheakEmail, trigger: 'blur'}
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: cheakMobile, trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    async resUserList() {
      const { data: res } = await getUserList(this.params)
      if (res.meta.status != 200) return this.$message.error('获取失败')
      this.userlist = res.data.users
      this.total = res.data.total
    },
    async UserStateChange(userinfo) {
      const {data: res} = await putChangeState({
        id: userinfo.id,
        type: userinfo.mg_state
      })
      // console.log(res);
      if(res.meta.status != 200) {
        userinfo.mg_state != userinfo.mg_state
        return this.$Message.error('状态修改失败')
      }
      console.log(this.$messageh);
      this.$Message.success('状态修改成功')
    },
    // async editUserRes(id) {
    //   // const {data: res} = await editUser(id)
    //   return await editUser(id)
    //   // this.editForm = res
    //   // console.log(res);
    // },
    handleSizeChange(newpage) {
      // console.log(newpage);
      // 打印多少条数据
      this.params.pagesize = newpage
      this.resUserList()
    },
    handleCurrentChange(newcur) {
      console.log(newcur);
      // 打印当前页码
      this.params.pagenum = newcur
      this.resUserList()
    },
    // 重置表单对话框
    addDialogClosed() {
      // 拿到表单 调用eleUI表单自带的自定义函数 回退到初始状态
      this.$refs.addFromRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFromRef.validate(async vaild => {
        if(!vaild) return 
        const {data: res} = await addUser(this.addForm) 
        if(res.meta.status != 201) return this.$Message.error('添加失败，请重试')
        this.resUserList()
        this.$Message.success('添加成功')
        this.addDialogVisible = false
      })
    },
    async showEditDialog(id) {
      console.log(id);
      const {data: res} = await getUserById(id)
      // console.log(id);
      // console.log(data);
      // console.log(this.editForm);
      if(res.meta.status != 200) return this.$Message.error('获取失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 重置修改的结果 即为如果我修改了 不合适我关了从新打开不提示
    editDialogClose() {
      this.$refs.editFromRef.resetFields()
    },
    // 修改用户信息并提交
    // 通过ElemUI中validate判断是否通过预验证 其中回调函数valid是一个布尔值 
    // 通过预验证返回true 不通过返回false
    editUserInfo() {
      this.$refs.editFromRef.validate(async valid => {
        if(!valid) return
        // 修改用户信息
        const {data: res} = await editUser(this.editForm.id,{
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        console.log(res);
        if(res.meta.status != 200) return this.$Message.error('修改失败,请重试')
        this.resUserList()
        this.$Message.success('修改成功')
        this.editDialogVisible = false
      })
    },
    async removeUserById(id) {
      const confirmresult = await this.$confirm('此操作将永久删除该用户, 是否继续','提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(confirmresult!= 'confirm') return this.$Message.info('已取消删除')
      // 如果同意删除  输出confirm
      // 如果不同已删除 输出cancel
      console.log(confirmresult + id);
      const {data: res} = await deleteUserReq(id)
      if(res.meta.status !=200) return this.$Message.error('删除失败')
      this.$Message.success('删除成功')
      this.resUserList()
    }
  },
}
</script>

<style>
</style>